#ifndef __GAME_ENGINE_H_
#define __GAME_ENGINE_H_

#include <boost/shared_ptr.hpp>
#include <list>
#include "MapProvider.h"
#include "Action.h"
#include "Decision.h"
#include "Unit.h"
#include "assert.h"

struct GameEngine
{
	bool makeAction(UnitBasePtr unit, ActionBasePtr action)
	{
		if (!action || !action->execute(mapProvider))
			return false;
		return true;
	}

	void runDecision(UnitBasePtr unit, DecisionBasePtr decision)
	{
		if (!decision) return;

		ActionBasePtr action;
		int count = 0;
		while (action = decision->nextAction())
		{
			if (!makeAction(unit, action))
			{
				unit->actionFail(count);
				count = -1;
				break;
			} else
				count++;
		}
		if (count >= 0) 
			unit->decisionSucceed(count);
	}

	void run()
	{
		while (unitList.size())
		{
			UnitBasePtr unit = unitList.front();
			unitList.pop_front();
			assert(unit);

			if (!unit->active())
				continue;

			DecisionBasePtr decision = unit->makeDecision(mapProvider);

			if (decision)
				runDecision(unit, decision);
			
			unitList.push_back(unit);
		}
	}

	UnitBaseList unitList;
	MapProvider mapProvider;
};

#endif